import { detailInfoService } from '@/services/supervisionApi';
import { useRequest } from 'ahooks';
import type { DescriptionsProps } from 'antd';
import { Button, Descriptions, Image, message } from 'antd';
import qrcode from 'qrcode-generator';
import React, { useEffect } from 'react';

interface ChildComponentProps {
  data: {
    id?: number;
    classroomLocation?: string;
    courseName?: string;
    classNumber?: string;
    instructor?: string;
    crewName?: string;
    created_at?: string;
    status?: string;
    remark?: string;
    upload?: string;
    courseId: number;
  };
}

const ChildComponent: React.FC<ChildComponentProps> = ({ data }) => {
  console.log('课程数据 >>> ', data);

  const [messageApi, contextHolder] = message.useMessage();
  const [supervisionInfo, setSupervisionInfo] = React.useState<any>({});

  // 发送请求
  const info = useRequest(detailInfoService, {
    manual: true,
    onSuccess: (data) => {
      console.log('课程详情 >>> ', data);
      setSupervisionInfo(data);
    },
  });

  useEffect(() => {
    info.run({
      courseId: data.courseId,
    });
  }, []);

  const items: DescriptionsProps['items'] = [
    {
      key: '1',
      label: '学院',
      children: supervisionInfo.college,
    },
    {
      key: '2',
      label: '星期',
      children: supervisionInfo.dayOfWeek,
    },
    {
      key: '3',
      label: '巡查节次',
      children: supervisionInfo.session,
    },
    {
      key: '4',
      label: '开课单位',
      children: supervisionInfo.courseOfferingUnit,
    },
    {
      key: '5',
      label: '授课教师',
      children: supervisionInfo.instructor,
    },
    {
      key: '6',
      label: '开课课程',
      children: supervisionInfo.courseName,
    },
    {
      key: '7',
      label: '班级名称',
      children: supervisionInfo.classNumber,
    },

    {
      key: '8',
      label: '上课地点',
      children: supervisionInfo.classroomLocation,
    },
    {
      key: '9',
      label: '早餐携带人数',
      children: supervisionInfo.breakfast,
    },
    {
      key: '10',
      label: '着装不规范人数',
      children: supervisionInfo.clothing,
    },
    {
      key: '11',
      label: '零食携带人数',
      children: supervisionInfo.snack,
    },
    {
      key: '12',
      label: '其他不良行为',
      children: supervisionInfo.badBehaviorRemark,
    },
    {
      key: '13',
      label: '抬头率高',
      children: supervisionInfo.lookUp,
    },
    {
      key: '14',
      label: '互动率高',
      children: supervisionInfo.interaction,
    },
    {
      key: '15',
      label: '其他优良行为',
      children: supervisionInfo.behaviorRemark,
    },
    {
      key: '16',
      label: '督导人员',
      children: supervisionInfo.crewName,
    },
    {
      key: '17',
      label: '创建时间',
      children: supervisionInfo.created_at,
    },
    {
      key: '18',
      label: '照片记录',
      children: data.upload ? (
        <Image.PreviewGroup
          preview={{
            onChange: (current, prev) =>
              console.log(`current index: ${current}, prev index: ${prev}`),
          }}
        >
          {JSON.parse(data.upload).map((src: string, index: any) => (
            // http://www.gameback.cn/tos-cn-i-trmyndwfss/1747961638589.jpg~tplv-trmyndwfss-image.image
            <Image
              key={index}
              height={200}
              width={200}
              src={`//www.gameback.cn/tos-cn-i-trmyndwfss/${src}~tplv-trmyndwfss-image.image`}
            />
          ))}
        </Image.PreviewGroup>
      ) : (
        <Image
          width={200}
          height={200}
          // src="error"
          fallback=""
        />
      ),
    },
  ];

  const handleCopyClick = async () => {
    try {
      // 1. 准备基础数据
      const imageUrls = data.upload ? JSON.parse(data.upload) : [];
      if (!imageUrls.length) {
        messageApi.warning('没有可用的图片数据');
        return;
      }

      for (let index = 0; index < imageUrls.length; index++) {
        // 2. 加载原始图片
        const img = await new Promise<HTMLImageElement>((resolve, reject) => {
          const image = document.createElement('img');
          image.crossOrigin = 'Anonymous';
          image.onload = () => resolve(image);
          image.onerror = reject;
          image.src = `//gameback.cn/static/${imageUrls[index]}`;
        });

        // 3. 创建Canvas
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d')!;

        // 4. 计算画布尺寸
        const INFO_HEIGHT = 200; // 信息区域高度
        canvas.width = img.width;
        canvas.height = img.height + INFO_HEIGHT;

        // 5. 绘制原始图片
        ctx.drawImage(img, 0, 0, img.width, img.height);

        // 6. 绘制信息区域背景
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, img.height, img.width, INFO_HEIGHT);

        // 7. 设置文字样式
        ctx.fillStyle = '#333333';
        ctx.font = '32px "Microsoft YaHei"';
        const lineHeight = 40;
        let textY = img.height + 30;

        // 8. 绘制文字信息
        const drawText = (text: string, x: number, y: number, maxWidth?: number) => {
          if (!maxWidth) {
            ctx.fillText(text, x, y);
            return y + lineHeight;
          }

          const words = text.split('');
          let line = '';
          for (const word of words) {
            const testLine = line + word;
            const metrics = ctx.measureText(testLine);
            if (metrics.width > maxWidth && line !== '') {
              ctx.fillText(line, x, y);
              line = word;
              y += lineHeight;
            } else {
              line = testLine;
            }
          }
          ctx.fillText(line, x, y);
          return y + lineHeight;
        };

        // 绘制多行信息
        textY = drawText(`授课教师：${data.instructor}`, 20, textY);
        textY = drawText(`上课班级：${data.classNumber}`, 20, textY);
        textY = drawText(`教室位置：${data.classroomLocation}`, 20, textY);
        textY = drawText(`备注信息：${data.remark}`, 20, textY, canvas.width - 180);

        // 9. 生成二维码
        const qrSize = 150;
        const qrMargin = 20;
        const qrCode = qrcode(0, 'M');
        qrCode.addData(window.location.href); // 使用当前页面URL或自定义链接
        qrCode.make();

        // 获取二维码模块数组
        const moduleCount = qrCode.getModuleCount();

        // 绘制二维码
        const cellSize = qrSize / moduleCount;
        ctx.fillStyle = '#000000';
        for (let y = 0; y < moduleCount; y++) {
          for (let x = 0; x < moduleCount; x++) {
            if (qrCode.isDark(y, x)) {
              // 检查模块是否为黑色
              ctx.fillRect(
                canvas.width - qrSize - qrMargin + x * cellSize,
                img.height + (INFO_HEIGHT - qrSize) / 2 + y * cellSize,
                cellSize,
                cellSize,
              );
            }
          }
        }
        // 10. 触发下载
        const link = document.createElement('a');
        link.download = `督导信息-${data.courseName}.png`;
        link.href = canvas.toDataURL('image/png');
        link.click();

        messageApi.success('图片生成成功！');
      }
    } catch (error) {
      console.error('生成失败:', error);
      messageApi.error('图片生成失败！');
    }
  };

  return (
    <Descriptions
      extra={
        <Button style={{ marginRight: '25px' }} type="primary" onClick={handleCopyClick}>
          复制
        </Button>
      }
      size="small"
      title="督导信息详情"
      bordered
      items={items}
    />
  );
};

export default ChildComponent;
